package cate.game.play.skill;

import cate.common.table.d.GDSkill;
import cate.game.play.base.TargetSelector;
import cate.game.play.config.skill.SkillCfg;
import cate.game.play.fighter.Fighter;
import cate.game.play.proce.move.MoveCtx;
import cate.game.play.skill.active.ActiveHandler;
import cate.game.play.skill.passive.PassiveHandler;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import org.springframework.data.annotation.Transient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@NoteClass("技能对象")
public class Skill {

	@NoteField("技能的模板ID")
	public int tid;

	@NoteField("技能的拥有者")
	@JsonIgnore
	@Transient
	public transient Fighter owner;

	@NoteField("技能配置")
	@JsonIgnore
	@Transient
	public transient SkillCfg cfg;

	@NoteField(value = "主动脚本处理器")
	@JsonIgnore
	@Transient
	public transient ActiveHandler active;

	@NoteField(value = "被动效果处理器")
	@JsonIgnore
	@Transient
	public transient PassiveHandler passive;

	@NoteField("技能临时参数")
	@JsonIgnore
	@Transient
	public transient SkillParam param = new SkillParam();

	public void reset(){
		param.reset();
	}


	public void setActive(ActiveHandler active) {
		if (active == null) {
			return;
		}
		this.active = active;
		this.active.setSkill(this);
	}


	public void setPassive(PassiveHandler passive) {
		if (passive == null) {
			return;
		}
		this.passive = passive;
		this.passive.setSkill(this);
	}


	/**
	 * 目标选择
	 */
	public List<Fighter> selectTargets(MoveCtx move, List<Fighter> extendTargets) {
		//优先使用技能指定的目标
		if (param.hasSelectTarget()) {
			return param.getAppointTargets();
		}
		move.getActor().skill.forHandlers(h -> h.beforeSelectTargets(move, this));
		switch (cfg.getRetarget()) {
			case GDSkill.Retarget.NO_RETARGET:
				return extendTargets;
			case GDSkill.Retarget.ORIGIN:
				return TargetSelector.findBySkill(move,this);
			case GDSkill.Retarget.NEAR:
			case GDSkill.Retarget.SAME_ROW:
			case GDSkill.Retarget.SAME_COL:
			case GDSkill.Retarget.OTHER:
				List<Fighter> targets = TargetSelector.findRetargetTargets(move.getTeamVS(), cfg.getRetarget(), extendTargets);
				final int tarNum = getTargetNum();
				if (tarNum > 0 && !targets.isEmpty() && targets.size() > tarNum) {
					Collections.shuffle(targets);
					targets = new ArrayList<>(targets.subList(0, tarNum));
				}
				return targets;
			case GDSkill.Retarget.RETARGET_WHEN_DIE:
				for (Fighter t : extendTargets) {
					if(t.isAlive()){
						return extendTargets;
					}
				}
				return TargetSelector.findBySkill(move,this);
			case GDSkill.Retarget.RETARGET_WHEN_NO_EMPTY:
				if(extendTargets.isEmpty()){
					return new ArrayList<>();
				}else {
					return TargetSelector.findBySkill(move,this);
				}
			default:
				return new ArrayList<>();
		}
	}


	/**
	 * 获取选择目标数量
	 * @return
	 */
	@JsonIgnore
	public int getTargetNum() {
		return cfg.getTargetNum() + param.getTargetNumAdd();
	}

}
